package com.libra.assemble.service.async;

import com.libra.assemble.xutil.email.AttachmentForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * Created by Libra on 15/10/23.
 */
@Component
@Transactional
public class AsyncService {

    private static final Logger logger = LoggerFactory.getLogger(AsyncService.class);

    @Async
    public void testAsyncMethod() {
        try {
            logger.info("进入异步！");
            //让程序暂停100秒，相当于执行一个很耗时的任务
            Thread.sleep(1000);
            logger.info("结束异步！");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Async
    public void saveAttachment(List<AttachmentForm> attachmentList){
        logger.info("进入异步！");
        try {
            logger.info("attachmentList size:{}", attachmentList.size());
            for (AttachmentForm attachmentForm : attachmentList) {
                saveAttachment(attachmentForm);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        logger.info("结束异步！");
    }



    private void saveAttachment(AttachmentForm attachmentForm) throws Exception {
        File file = new File(attachmentForm.getPhysicsPath());
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(file));
            bis = new BufferedInputStream(attachmentForm.getInputStream());
            int c;
            while ((c = bis.read()) != -1) {
                bos.write(c);
                bos.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bos.close();
            bis.close();
        }
    }
}
